package com.seal.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IProductTemplateDao;
import com.seal.dto.ProductTemplateDto;
import com.seal.model.ProductTemplate;

@Repository("productTemplateDaoImpl")
@SuppressWarnings("unchecked")
public class ProductTemplateDaoImpl extends BaseDaoImpl implements IProductTemplateDao{

	public void addProductTemplate(ProductTemplate ca) throws Exception {
		this.save(ca);
	}

	public void updateProductTemplate(ProductTemplate ca) throws Exception {
		this.update(ca);
	}
	
	public void deleteProductTemplate(ProductTemplate ca) throws Exception {
		this.delete(ca);
	}
	
	public ProductTemplate getProductTemplateById(Long id) throws Exception {
		return (ProductTemplate) this.select(ProductTemplate.class, id);
	}
	
	public List<ProductTemplate> getAllProductTemplate(ProductTemplateDto dto, Page page)throws Exception {
		StringBuffer hql=new StringBuffer("from ProductTemplate t where 1=1");
		if (null != dto.getFromDate()) {
			hql.append(" and t.startDate <= :fromDate");
		}
		
		if (null != dto.getToDate()) {
			hql.append(" and t.endDate >= :toDate");
		}
		
		if (null != dto.getStatus()) {
			hql.append(" and t.status = :status");
		}
		
		if(null != dto.getSid()){
			hql.append(" and t.sid = :sid");
		}
		
		if (!StringUtils.isEmpty(dto.getProductName())) {
			dto.setProductName("%"+dto.getProductName().trim()+"%");
			hql.append(" and t.productName like :productName");
		}

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(dto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql="select count(t) "+hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(dto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult().toString()));
		}
		
		return query.list();
	}
	
}
